﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Net;
using System.Xml;
using Kiiro.Model;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Microsoft.SharePoint;


namespace Kiiro.WebServices
{


    [Serializable]
    public class KiiroProjectStatusFlags
    {
        public bool ProjectURLAlreadyExists = false;
        public bool ProjectDoesNotExist = false;
        public bool UserDoesNotExist = false;
        public bool ExceptionOccurred = false;
        public string Exception;
        public bool Success = false;
    }

    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://mykiiro.com/project")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class KiiroProject : System.Web.Services.WebService
    {

        [WebMethod]
        public void CreateProject(string projectTitle, string projectSiteName,  int createdBySPUserID, DateTime createdDate, DateTime modifiedDate, bool deleteExisting, out KiiroProjectStatusFlags status)
        {
            
            Guid siteCollectionId;
            string serverRelativeUrl =  null;
            status = new KiiroProjectStatusFlags();
            Project project = null;            
            status.Success = true;
            
            try
            {
                //try and get the site collection ID and relative URL
                SPHelpers.GetSiteCollectionIdAndServerRelativeUrl(Context.Request.Url.Scheme + "://" + Context.Request.Url.Authority + Context.Request.RawUrl, out siteCollectionId, out serverRelativeUrl);


                //try and find the user provided
                User user = UserModel.GetOrCreateUser(createdBySPUserID, siteCollectionId, serverRelativeUrl);

                if (user == null)
                {
                    status.UserDoesNotExist = true;
                    status.Success = false;
                }

                if (status.Success)
                {

                    //check that the project url does not already exist
                    if (WebServicesHelper.DoesProjectExist(projectSiteName, siteCollectionId, serverRelativeUrl))
                    {
                        //check if we should delete the project first
                        if (deleteExisting)
                        {
                            project = ProjectsModel.GetByServerRelativeWebUrl(siteCollectionId, serverRelativeUrl + "/" + projectSiteName);        
                            project.EditType = EditType.Deleted;
                            project.ModifiedBy = user;
                            ProjectsModel.Save(project, siteCollectionId, serverRelativeUrl);
                        }
                        else
                        {
                            status.ProjectURLAlreadyExists = true;
                            status.Success = false;
                        }
                    }
                }
                
                if (status.Success)
                {

                
                    //create a new project
                    project = new Project();
                    if (projectTitle.Length > 255)
                        projectTitle = projectTitle.Substring(0, 255);

                    project.Title = projectTitle;
                    project.ServerRelativeUrl = serverRelativeUrl;
                    project.ServerRelativeWebUrl = projectSiteName;
                    project.SiteCollectionId = siteCollectionId;
                    project.EditType = EditType.Created;
                    project.ProjectStatus = ProjectStatus.Active;
                    project.CreatedBy = user;
                    project.CreatedDate = createdDate;
                    project.ModifiedDate = modifiedDate;

                    //save the project
                    ProjectsModel.Save(project, siteCollectionId, serverRelativeUrl);                                   
                }
            }
            catch(Exception ex)
            {
                status.ExceptionOccurred = true;
                status.Exception = ex.ToString();
                status.Success = false;
            }
        }

      

       

        [WebMethod]
        public void AddTeamMembersToProject(string projectSiteName, int createdBySPUserID, string SPUserIDs, out KiiroProjectStatusFlags status)
        {
            Guid siteCollectionId;
            string serverRelativeUrl = null;
            status = new KiiroProjectStatusFlags();
            Project project = null;
            status.Success = true;
            string[] users = SPUserIDs.Split( ",".ToCharArray());
            TeamMember member = null;
            User createdBy = null;

            try
            {
                //try and get the site collection ID and relative URL
                SPHelpers.GetSiteCollectionIdAndServerRelativeUrl(Context.Request.Url.Scheme + "://" + Context.Request.Url.Authority + Context.Request.RawUrl, out siteCollectionId, out serverRelativeUrl);
                

                //check that the project url does not already exist                
                if (!WebServicesHelper.DoesProjectExist(projectSiteName, siteCollectionId, serverRelativeUrl))
                {
                    status.ProjectDoesNotExist = true;
                    status.Success = false;                   
                }
                else
                {
                    project = ProjectsModel.GetByServerRelativeWebUrl(siteCollectionId, serverRelativeUrl + "/" + projectSiteName);

                    //get the created by
                    createdBy = UserModel.GetOrCreateUser(createdBySPUserID, siteCollectionId, serverRelativeUrl + "/" + projectSiteName);
                    
                    //add each user to the team
                    User user = null;
                    Boolean createMember = true;

                    foreach (string userID in users)
                    {
                        createMember = true;
                        user = UserModel.GetOrCreateUser(Int32.Parse(userID), siteCollectionId, serverRelativeUrl + "/" + projectSiteName);
                        if (user == null)
                        {
                            status.UserDoesNotExist = true;
                            status.Success = false;
                            createMember = false;
                        }

                        if (createMember)
                        {

                            //don't continue if the user is already a member of the project
                            foreach (int id in user.ProjectIds)
                            {
                                if (id == project.Id)
                                {
                                    createMember = false;
                                    break;
                                }
                            }

                            //create a new team member
                            if (createMember)
                            {
                                member = new TeamMember();
                                member.User = user;
                                member.UserId = user.Id;
                                member.CreatedBy = createdBy;
                                member.CreatedDate = DateTime.Now;
                                member.IsProjectManager = false;
                                member.ServerRelativeUrl = serverRelativeUrl;
                                member.SiteCollectionId = siteCollectionId;
                                member.ModifiedBy = createdBy;
                                member.ModifiedDate = DateTime.Now;
                                member.EditType = EditType.Created;
                                TeamModel.Save(member, siteCollectionId, serverRelativeUrl + "/" + projectSiteName);
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                status.ExceptionOccurred = true;
                status.Exception = ex.ToString();
                status.Success = false;
            }

        }
       
    
    }
}
